package com.je.gateway.filter;

import com.je.common.auth.HtmlView;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.buffer.impl.BufferImpl;
import org.apache.servicecomb.common.rest.RestConst;
import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
import org.apache.servicecomb.swagger.invocation.Response;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;

/**
 * html view
 */
public class GatewayHtmlViewServerFilter implements HttpServerFilter {

    @Override
    public int getOrder() {
        return -99;
    }

    @Override
    public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
        return null;
    }

    @Override
    public void beforeSendResponse(Invocation invocation, HttpServletResponseEx responseEx) {
        if (invocation.getContext().containsKey(HtmlView.HTML_VIEW)) {
            responseEx.setContentType("text/html;charset=utf-8");
        }
    }

    @Override
    public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) {
        Response response = (Response) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE);
        CompletableFuture<Void> future = new CompletableFuture<>();
        try {
            if (invocation!=null && invocation.getContext().containsKey(HtmlView.HTML_VIEW)) {
                responseEx.setContentType("text/html;charset=utf-8");
                String result = response.getResult();
                Buffer buffer = new BufferImpl();
                buffer.appendBytes(result.getBytes(StandardCharsets.UTF_8));
                responseEx.setBodyBuffer(buffer);
            }
            future.complete(null);
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
        return future;
    }

}
